<?php

namespace app\admin\controller;

use app\admin\library\Excel;
use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;
use app\admin\model\Codelib;
/**
 * 罐箱
 *
 */
class XPot extends Backend
{
    /**
     * XPot模型对象
     * @var \app\admin\model\XPot
     */
    protected $model = null;
    
    protected $quickSearchField = ['TCNO'];

    protected $defaultSortField = 'ID,desc';
    protected $noNeedLogin      = ['*'];

    protected $preExcludeFields = [''];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\XPot;
    }
    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $sy_type=$this->request->get('code');
        $sy_where='';
        if($sy_type && $sy_type=='GXNJ'){
            $sy_where="exists  (select * from (select tcno,MAX(nextcheckdate) as checkdate from X_POTCHECK group by tcno) a where a.tcno=x_pot.tcno and datediff(day,getdate(),a.checkdate)<(select isnull(max(CAST(attr as int)),0) from codelib where code='GXNJ' and codetype='alarmsetup'))";
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->where($sy_where)
//            ->order($order)
            ->paginate($limit)->toArray();
        $code=new Codelib();
        //设备状态
        $status=$code->where('codetype','potstatus')->column('codename','code');
        //罐箱种类
        $kind=$code->where('codetype','potkind')->column('codename','code');
        foreach ($res['data'] as &$v) {
            foreach ($status as $k=>$s) {
              if($v['STATUS']==$k){
                  $v['STATUS']=$s;
              }
            }
            foreach ($kind as $k=>$s) {
                if($v['KIND']==$k){
                    $v['KIND']=$s;
                }
            }
        }
        $this->success('', [
            'list'   => $res['data'],
            'total'  => $res['total'],
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $data['GXCGQPZ']=isset($data['GXCGQPZ'])?implode(',',$data['GXCGQPZ']):'';
            $data['GXJRFS']=isset($data['GXJRFS'])?implode(',',$data['GXJRFS']):'';
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }
    /**
     * 编辑
     */
    public function edit()
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $data['GXCGQPZ']=isset($data['GXCGQPZ'])?implode(',',$data['GXCGQPZ']):'';
            $data['GXJRFS']=isset($data['GXJRFS'])?implode(',',$data['GXJRFS']):'';
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }
        $row['GXCGQPZ']=empty($row['GXCGQPZ'])?:explode(',',$row['GXCGQPZ']);
        $row['GXJRFS']=empty($row['GXJRFS'])?:explode(',',$row['GXJRFS']);
        $this->success('', [
            'row' => $row
        ]);
    }
    /**
     * 导出
     */
    public function out(){
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $sy_type=$this->request->get('code');
        $sy_where='';
        if($sy_type && $sy_type=='GXNJ'){
            $sy_where="exists  (select * from (select tcno,MAX(nextcheckdate) as checkdate from X_POTCHECK group by tcno) a where a.tcno=x_pot.tcno and datediff(day,getdate(),a.checkdate)<(select isnull(max(CAST(attr as int)),0) from codelib where code='GXNJ' and codetype='alarmsetup'))";
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $data = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->where($sy_where)
            ->select()->toArray();
        $code=new Codelib();
        //设备状态
        $status=$code->where('codetype','potstatus')->column('codename','code');
        //罐箱种类
        $kind=$code->where('codetype','potkind')->column('codename','code');
        foreach ($data as &$v) {
            foreach ($status as $k=>$s) {
                if($v['STATUS']==$k){
                    $v['STATUS']=$s;
                }
            }
            foreach ($kind as $k=>$s) {
                if($v['KIND']==$k){
                    $v['KIND']=$s;
                }
            }
        }
        $head=['箱号','所有者','罐箱类型','设备状态'];
        $key=['TCNO','OWER','KIND','STATUS'];

        Excel::downloadExcel('年检导出',$data,$head,$key);

    }
}